import axios from "axios";
import router from "@/router";

// 配置axios 的属性

axios.defaults.timeout = 6000 // 1 分钟
axios.defaults.baseURL = 'http://localhost:8081'
axios.defaults.responseType = "json"

// 配置拦截器
axios.interceptors.request.use(
    req=>{
        req.headers["token"] = sessionStorage.getItem("token");
        return Promise.resolve(req);
    }
);

axios.interceptors.response.use(
    response =>{
        const {code} = response.data;
        if (code === 205){
            return refresh().then(result =>{
                let token = result.data.data;
                if (token !=null && token !== ""){
                    sessionStorage.setItem("token", token);
                    const config = response.config;
                    config.headers['token'] = token;
                    return axios(config);
                }else {
                    window.location.href = '/login'
                }
            });
        }
        return response;
    },
    error => {
        return Promise.reject(error);
    }
)

export function refresh(){
    return axios({
        url: '/refresh',
        method: 'post',
        params: {refreshToken :sessionStorage.getItem("refreshToken")}
    })
}

export default axios;
